<?php

namespace App\Models;

use http\Env\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use App\Models\GoodCart;
use App\Models\Goods;
use App\Models\GoodCartStandard;
use App\Models\CustomerAppletsUserOrderGoods;
use App\Models\CustomerAppletsUserOrderGoodStandards;
use App\Models\CustomerAppletsUserAddress;

class CustomerAppletsUserOrders extends Model
{
    protected $table      = "customerapplets_user_orders";
    protected $primaryKey = "id";

    /**
     * 查询订单数据
     * @param $user_id
     * @param $store_id
     * @param $order_pay_status
     * @return mixed
     */
    public function getOrderData($user_id,$store_id,$order_pay_status){

        $orderData = $this
            ->select("id","store_id","user_id","out_trade_no","order_pay_status","order_type")
            ->where(['user_id' => $user_id , 'store_id' => $store_id]);
        if($order_pay_status != "all"){
            $orderData = $orderData->where(['order_pay_status' => $order_pay_status]);
        }

        $orderData = $orderData->orderBy("created_at","desc")->paginate(20);

        if(!empty($orderData)){

            foreach ($orderData as $key => $val){

                $goodData = DB::table("customerapplets_user_order_goods")
                    ->select("customerapplets_user_order_goods.good_id","customerapplets_user_order_goods.good_price","customerapplets_user_order_goods.good_num","customerapplets_user_order_goods.good_money","goods.main_image","goods.name")
                    ->leftJoin("goods","goods.id","=","customerapplets_user_order_goods.good_id")
                    ->where(['customerapplets_user_order_goods.order_id' => $val['id'] , 'customerapplets_user_order_goods.store_id' => $val['store_id']])->get();

                $val->good = $goodData;
            }

        }

        return $orderData;
    }


    /**
     * 查询商家订单数据
     * @param $store_id
     * @param string $created_at
     * @param string $out_trade_no
     * @param string $order_pay_status
     * @return mixed
     */
    public function getStoreOrderData($store_id,$created_at = "",$out_trade_no = "",$order_pay_status = ""){

        $orderData = $this
            ->select("id","store_id","table_id","user_id","order_total_money","order_pay_money","out_trade_no","order_pay_status","order_type","packing_fee","created_at")
            ->where(['store_id' => $store_id]);
        if(!empty($created_at)){
            $orderData = $orderData->where('created_at','>',$created_at.' 00:00:00')->where('created_at','<=',$created_at.' 23:59:59');
        }

        if(!empty($out_trade_no)){
            $orderData->where(function($query) use ($out_trade_no) {
                $query->where('out_trade_no','like','%'.$out_trade_no.'%');
            });
        }

        if(!empty($order_pay_status)){
            $orderData = $orderData->where(['order_pay_status' => $order_pay_status]);
        }

        $orderData = $orderData->orderBy("created_at","desc")->paginate(20);

        if(!empty($orderData)){

            foreach ($orderData as $key => $val){
                //查询订单创建人
                $user_info = DB::table("customerapplets_users")
                    ->select("customerapplets_user_wechats.wechat_mobile")
                    ->leftJoin("customerapplets_user_wechats","customerapplets_users.id","=","customerapplets_user_wechats.user_id")
                    ->where(['customerapplets_users.id' => $val->user_id])
                    ->first();
                if(!empty($user_info)){
                    $val->user_mobile = $user_info->wechat_mobile;
                }else{
                    $val->user_mobile = "";
                }

                //查询商品
                $goodData = DB::table("customerapplets_user_order_goods")
                    ->select("customerapplets_user_order_goods.good_id","customerapplets_user_order_goods.good_price","customerapplets_user_order_goods.good_num","customerapplets_user_order_goods.good_money","goods.main_image","goods.name")
                    ->leftJoin("goods","goods.id","=","customerapplets_user_order_goods.good_id")
                    ->where(['customerapplets_user_order_goods.order_id' => $val['id'] , 'customerapplets_user_order_goods.store_id' => $val['store_id']])->get();

                $val->good = $goodData;
            }

        }

        return $orderData;
    }

    /**
     * 更新订单的状态
     * @param $store_id
     * @param $order_id
     * @param $out_trade_no
     * @param $order_pay_status
     * @param string $refund
     * @return array
     */
    public function updateStoreOrderData($store_id,$order_id,$out_trade_no,$order_pay_status,$refund = ""){
        $orderData = $this
            ->select("id","store_id","user_id","out_trade_no","order_pay_status","order_type")
            ->where(['store_id' => $store_id,'id' => $order_id , 'out_trade_no' => $out_trade_no])
            ->first();
        if(empty($orderData)){
            return ['status' => 202 , 'message' => '订单数据不存在'];
        }else{
            if($order_pay_status == 3){
                if($orderData->order_pay_status == 4 || $orderData->order_pay_status == 5 || $orderData->order_pay_status == 6){
                    return ['status' => 202 , 'message' => '订单不可取消'];
                }else{
                    $updateOrderResult = $this->where(['store_id' => $store_id,'id' => $order_id , 'out_trade_no' => $out_trade_no])->update([
                        'order_cancel_time' => date("Y-m-d H:i:s",time()),
                        'order_refund_reason' => $refund['order_refund_reason'],
                        'order_pay_status'  => 3,
                        'updated_at'        => date("Y-m-d H:i:s",time()),
                    ]);
                }
            }else if($order_pay_status == 5){
                $updateOrderResult = $this->where(['store_id' => $store_id,'id' => $order_id , 'out_trade_no' => $out_trade_no])->update([
                    'order_pay_status'  => 5,
                    'updated_at'        => date("Y-m-d H:i:s",time()),
                ]);
            }else if($order_pay_status == 6){
                if($orderData->order_pay_status == 4 || $orderData->order_pay_status == 5 || $orderData->order_pay_status == 6){
                    return ['status' => 202 , 'message' => '订单不可退款'];
                }else{
                    $updateOrderResult = $this->where(['store_id' => $store_id,'id' => $order_id , 'out_trade_no' => $out_trade_no])->update([
                        'order_refund_time' => date("Y-m-d H:i:s",time()),
                        'order_refund_reason' => $refund['order_refund_reason'],
                        'order_refund_dis'    => $refund['order_refund_dis'],
                        'order_pay_status'  => 6,
                        'updated_at'        => date("Y-m-d H:i:s",time()),
                    ]);
                }
            }
            if($updateOrderResult){
                return ['status' => 200 , 'message' => '更新成功'];
            }else{
                return ['status' => 202 , 'message' => '更新失败'];
            }
        }
    }

    /**
     * 订单详情信息
     * @param string $user_id
     * @param $store_id
     * @param $order_id
     * @return mixed
     */
    public function getOrderDetailData($user_id = "",$store_id,$order_id){

        $orderInfo = $this
            ->select("id","out_trade_no","order_pay_status","order_type","delivery_method","self_raising_order_time","self_raising_order_mobile","address_id","delivery_fee","packing_fee","is_use_coupon","coupon_id","coupon_source","order_total_money","use_coupon_money","order_remarks","order_pay_money","created_at","order_pay_type","order_pay_success_time","dm_id","dm_name","dm_mobile")
            ->where(['store_id' => $store_id,'id' =>$order_id]);
        if(!empty($user_id)){
            $orderInfo = $orderInfo->where(['user_id' => $user_id]);
        }
        $orderInfo = $orderInfo->first();

        $goodData = DB::table("customerapplets_user_order_goods")
            ->select("customerapplets_user_order_goods.good_id","customerapplets_user_order_goods.good_price","customerapplets_user_order_goods.good_num","customerapplets_user_order_goods.good_money","goods.main_image","goods.name")
            ->leftJoin("goods","goods.id","=","customerapplets_user_order_goods.good_id")
            ->where(['customerapplets_user_order_goods.order_id' => $order_id , 'customerapplets_user_order_goods.store_id' => $store_id])->get();


        if($orderInfo -> order_type == 1){

            $customerAppletsUserAddressModel = new CustomerAppletsUserAddress();

            $address = $customerAppletsUserAddressModel->getUserAddressFirst($orderInfo->address_id);

            $orderInfo->address = $address;

            if($orderInfo -> delivery_method == 2){
                $dadaOrderData = DB::table("dada_orders")->where(['out_trade_no' => $orderInfo->out_trade_no])->first();
                if(!empty($dadaOrderData)){
                    $orderInfo->dada_order_id = $dadaOrderData->origin_id;
                }else{
                    $orderInfo->dada_order_id = "";
                }
            }else{
                $orderInfo->dada_order_id = "";
            }
        }else{
            $orderInfo->dada_order_id = "";
        }

        $orderInfo->good = $goodData;

        return $orderInfo;
    }

    /**
     * 生成订单
     * @param $requestData
     * @return array|bool
     */
    public function generateOrderData($requestData){

        $orderData['store_id']          = $requestData['store_id'];
        $orderData['user_id']           = $requestData['user_id'];
        $orderData['out_trade_no']      = $requestData['out_trade_no'];

        $orderData['order_type']        = $requestData['order_type'];
        $orderData['user_pay_type']     = $requestData['user_pay_type'];
        // 桌号id
        $orderData['table_id']          = isset($requestData['table_id']) ?? 0;
        // 如果是扫码点餐，状态直接是已完成
        if (isset($orderData['code_order_type'])) {
            if ($orderData['code_order_type'] == 1 && !empty($orderData['table_id'])) {
                $orderData['order_pay_status']  = 11;
            }
        } else {
            $orderData['order_pay_status']  = 1;
        }

        if($requestData['order_type'] == 1){
            //说明是外卖订单
            $orderData['address_id']    = $requestData['address_id'];
            $orderData['delivery_fee']  = $requestData['delivery_fee'];

        }else{
            //说明自提订单
            $orderData['self_raising_order_mobile']     = $requestData['self_raising_order_mobile'];
        }

        $orderData['packing_fee']                   = $requestData['packing_fee'];
        $orderData['self_raising_order_time']       = $requestData['self_raising_order_time'];
        $orderData['is_use_coupon']                 = $requestData['is_use_coupon'];

        if($requestData['is_use_coupon'] == 1){
            //说明使用了优惠券
            $orderData['coupon_id']         = $requestData['coupon_id'];
            $orderData['coupon_source']     = $requestData['coupon_source'];
            $orderData['use_coupon_money']  = $requestData['use_coupon_money'];
        }

        $orderData['order_total_money'] = $requestData['order_total_money'];
        $orderData['order_remarks']     = isset($requestData['order_remarks']) ? $requestData['order_remarks'] : "";
        $orderData['order_pay_money']   = $requestData['order_pay_money'];
        $orderData['created_user']      = $requestData['user_id'];
        $orderData['updated_user']      = $requestData['user_id'];
        $orderData['created_at']        = date("Y-m-d H:i:s",time());
        $orderData['updated_at']        = date("Y-m-d H:i:s",time());

        //开启事务
        DB::beginTransaction();

        try{

            $order_id           = $this->insertGetId($orderData);

            if($order_id){

                //商品规格
                $goodCartStandardModel  = new GoodCartStandard();
                //商品购物车
                $goodCartModel          = new GoodCart();

                $goodCartResult         = $goodCartModel->where(['user_id' => $requestData['user_id'],'store_id' => $requestData['store_id']])->get();

                if(!empty($goodCartResult)){

                    //订单中的商品数据储存
                    $orderGoodData          = [];

                    //订单中的商品规格数据储存
                    $orderGoodStandardData  = [];

                    $goodModel              = new Goods();

                    foreach ($goodCartResult as $key => $val){

                        if($val['num'] > 0){

                            $goodResult = $goodModel->select("id","price")->where(['id' => $val['good_id']])->first();

                            $goodCartStandardResult = $goodCartStandardModel->where(['cart_id' => $val['id'],'good_id' => $val['good_id']])->get();

                            if(!empty($goodCartStandardResult)){

                                foreach ($goodCartStandardResult as $k => $v){

                                    $orderGoodStandardCartData['order_id']      = $order_id;
                                    $orderGoodStandardCartData['good_id']       = $val['good_id'];
                                    $orderGoodStandardCartData['stand_id']      = $v['stand_id'];
                                    $orderGoodStandardCartData['created_user']  = $requestData['user_id'];
                                    $orderGoodStandardCartData['updated_user']  = $requestData['user_id'];
                                    $orderGoodStandardCartData['created_at']    = date("Y-m-d H:i:s",time());
                                    $orderGoodStandardCartData['updated_at']    = date("Y-m-d H:i:s",time());

                                    array_push($orderGoodStandardData,$orderGoodStandardCartData);
                                }

                            }

                            $orderGoodFirstData['order_id']         = $order_id;
                            $orderGoodFirstData['out_trade_no']     = $requestData['out_trade_no'];
                            $orderGoodFirstData['store_id']         = $requestData['store_id'];
                            $orderGoodFirstData['good_id']          = $val['good_id'];
                            $orderGoodFirstData['good_price']       = $goodResult->price;
                            $orderGoodFirstData['good_num']         = $val['num'];
                            $orderGoodFirstData['good_money']       = $goodResult->price * intval($val['num']);
                            $orderGoodFirstData['created_user']     = $requestData['user_id'];
                            $orderGoodFirstData['updated_user']     = $requestData['user_id'];
                            $orderGoodFirstData['created_at']       = date("Y-m-d H:i:s",time());
                            $orderGoodFirstData['updated_at']       = date("Y-m-d H:i:s",time());

                            array_push($orderGoodData,$orderGoodFirstData);

                        }

                    }

                    $customerAppletsUserOrderGoodsModel     = new CustomerAppletsUserOrderGoods();

                    //添加订单中的商品数据
                    $customerAppletsUserOrderGoodAddResult  = $customerAppletsUserOrderGoodsModel->insert($orderGoodData);

                    if($customerAppletsUserOrderGoodAddResult){

                        $customerAppletsUserOrderGoodStandardModel     = new CustomerAppletsUserOrderGoodStandards();

                        //添加订单中商品的规格数据
                        $result = $customerAppletsUserOrderGoodStandardModel->insert($orderGoodStandardData);

                        // if(!$result){
                        //     return ["status" => 202,"message" => "订单商品规格数据创建失败"];
                        // }else{
                        //
                        //     //删除掉购物车的数据
                        //     $goodCartDeleteResult         = $goodCartModel->where(['user_id' => $requestData['user_id'],'store_id' => $requestData['store_id']])->delete();
                        //
                        //     if(!$goodCartDeleteResult){
                        //         return ["status" => 202,"message" => "删除购物车数据失败"];
                        //     }
                        //
                        //     foreach ($goodCartResult as $cart_key => $cart_val){
                        //
                        //         $goodCartStandardDeleteResult = $goodCartStandardModel->where(['cart_id' => $cart_val['id'],'good_id' => $cart_val['good_id']])->get();
                        //
                        //         if(!empty($goodCartStandardDeleteResult) && count($goodCartStandardDeleteResult) > 0){
                        //
                        //             $goodCartStandardModel->where(['cart_id' => $cart_val['id'],'good_id' => $cart_val['good_id']])->delete();
                        //
                        //         }
                        //     }
                        //
                        // }

                        //判断是否是用户余额支付
                        /**
                        if($requestData['user_pay_type'] == 1){
                            switch ($requestData['terminal_type']){
                                //微信
                                case config("api.weChat"):

                                    $userMemberList = DB::table("member_lists")->select("mb_money","pay_counts","pay_moneys","updated_at","xcx_openid","wx_openid","ali_user_id")
                                        ->where(['xcx_openid' => $requestData['openid']])->first();
                                    $mb_money   = number_format($userMemberList->mb_money,2) - number_format($requestData['order_pay_money'],2);
                                    $pay_counts = intval($userMemberList->pay_counts) + 1;
                                    $pay_moneys = $userMemberList->pay_moneys + number_format($requestData['order_pay_money'],2);

                                    DB::table("member_lists")->where(['xcx_openid' => $requestData['openid']])->update([
                                        'mb_money'   => $mb_money,
                                        'pay_counts' => $pay_counts,
                                        'pay_moneys' => $pay_moneys,
                                        'updated_at' => date("Y-m-d H:i:s",time())
                                    ]);

                                    break;
                                //支付宝
                                case config("api.aliPay"):

                                    $userMemberList = DB::table("member_lists")->select("mb_money","pay_counts","pay_moneys","updated_at","xcx_openid","wx_openid","ali_user_id")
                                        ->where(['ali_user_id' => $requestData['openid']])->first();
                                    $mb_money   = number_format($userMemberList->mb_money,2) - number_format($requestData['order_pay_money'],2);
                                    $pay_counts = intval($userMemberList->pay_counts) + 1;
                                    $pay_moneys = $userMemberList->pay_moneys + number_format($requestData['order_pay_money'],2);

                                    DB::table("member_lists")->where(['ali_user_id' => $requestData['openid']])->update([
                                        'mb_money'   => $mb_money,
                                        'pay_counts' => $pay_counts,
                                        'pay_moneys' => $pay_moneys,
                                        'updated_at' => date("Y-m-d H:i:s",time())
                                    ]);

                                    break;
                            }
                        }
                         **/

                    }else{
                        return ["status" => 202,"message" => "订单商品数据创建失败"];
                    }
                }
            }else{
                return ["status" => 202,"message" => "订单创建失败"];
            }

            DB::commit();
            return ["status" => 200,"message" => ["order_id" => $order_id, "end_date" => date("Y-m-d H:i:s",time()+15*60)]];
        }catch (\Exception $e) {
            DB::rollBack();
            return ["status" => 202,"message" => $e->getMessage()];
        }

    }

    // 搜索条件
    private function getMap($input)
    {
        $map = [];
        // 订单id
        if (!empty($input['order_id'])) {
            $map['id'] = $input['order_id'];
        }

        return $map;
    }

    // 查询订单信息
    public function getOrderInfo($input)
    {
        $map = $this->getMap($input);

        return $this->where($map)->first();
    }

    // 完成订单支付
    public function donePayOrder($input, $data)
    {
        $map = $this->getMap($input);

        return $this->where($input)->update($data);
    }

}
